<template>
  <a-modal
    title="上传附件"
    :width="810"
    :visible="visible"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
    </template>
    <a-card>
      <a-upload
        :disabled="fileList.length > 9 || loading"
        :file-list="fileList"
        :multiple="true"
        :remove="handleRemove"
        :before-upload="beforeUpload"
        @change="handleChange">
        <a-button>
          <a-icon type="upload"/>
          选择文件（最多10个）
        </a-button>
      </a-upload>
    </a-card>
  </a-modal>
</template>

<script>
import { addCPFile, queryCPFile, removeCPFile } from '@/api/vote/candidate'

export default {
  name: 'SelectFiles',
  data() {
    return {
      visible: false,
      // visible: true,
      cp: {},
      fileList: [],
      uploading: false,
      loading: false
    }
  },
  methods: {
    addFile(record) {
      this.visible = true
      this.cp = record
      this.loading = true
      this.fileList = []
      const that = this
      this.loading = true
      queryCPFile(this.cp).then(res => {
        console.log(res)
        if (res.result !== null && res.result.length > 0) {
          const files = res.result.toString().split(',')
          for (let i = 0; i < files.length; i++) {
            const file = files[i]
            that.fileList.push({
              uid: i + 1,
              status: 'done',
              name: file.substr(file.lastIndexOf('/') + 1),
              url: file
            })
          }
        }
        that.loading = false
      }).catch(err => {
        that.loading = false
        that.$message.error(err.result)
        that.visible = false
      })
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      removeCPFile({ file: file.url }).then((res) => {
        if (res.message === 'error') {
          this.$message.error('服务器删除错误')
        } else {
          this.$message.success('服务器删除成功')
        }
      }).catch((err) => {
        console.log(err)
      })
      this.removeFromList(index)
    },
    removeFromList (index) {
      this.fileList.splice(index, 1)
    },
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('请上传大小在 10MB内的文件!')
      }
      if (isLt10M) {
        file.url = ''
        this.fileList = [...this.fileList, file]
        this.canUpload = true
      } else {
        this.canUpload = false
      }
      return false
    },
    updateFile(index) {
      const item = this.fileList[index]
      const formData = new FormData()
      formData.append('data', JSON.stringify(this.cp))
      formData.append('file', item)
      const that = this
      this.uploading = true
      addCPFile(formData).then(res => {
        that.$message.success(`${item.name} 文件上传成功`)
        item.url = res.result
        console.log(item.url)
        that.uploading = false
      }).catch(err => {
        that.$message.error(err.result || `${item.name} 文件上传失败`)
        that.removeFromList(index)
        console.log(err)
        that.uploading = false
      })
    },
    handleChange(item) {
      if (this.canUpload) {
        const index = this.fileList.indexOf(item.file)
        this.updateFile(index)
      }
    },
    // handleOK() {
    //   this.$emit('ok')
    // },
    handleCancel () {
      this.visible = false
    }
  },
}
</script>

<style scoped>

</style>
